package com.wa.mapper.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * @author WangPengfei
 * @date 2018/7/24
 */
@MapperScan(basePackages = "com.wa", sqlSessionFactoryRef = "davmSqlSessionFactory")
@Configuration
public class DavmMybatisConfig {

    @Bean(name = "davmDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.davm")
    public DataSource davmDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "davmSqlSessionFactory")
    public SqlSessionFactory davmSqlSessionFactory(@Qualifier("davmDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        bean.setDataSource(dataSource);
        Interceptor[] interceptors = new Interceptor[2];
        // 更新时间插件
        interceptors[0] = new MybatisUpdatePlugin();
        // 基础查询删除状态过滤
        interceptors[1] = new MybatisSelectPlugin();
        bean.setPlugins(interceptors);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }

    @Bean(name = "davmTransactionManager")
    public PlatformTransactionManager annotationDrivenTransactionManager(@Qualifier("davmDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("davmSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }


}
